package org.mrjbee.share.it.easy.client.daemon.notification;

import java.awt.AWTException;
import java.awt.SystemTray;
import java.awt.TrayIcon;
import java.awt.TrayIcon.MessageType;
import java.io.IOException;

import javax.swing.ImageIcon;

import org.mrjbee.share.it.easy.client.daemon.ConfigurationProvider;
import org.mrjbee.share.it.easy.client.daemon.Log;

//,"notify-send|||{msg}|||{body}"
public class NotificationManager {
	
	private String cmdPattern;
	private TrayIcon trayIcon;
	public void init(ConfigurationProvider conf) {
		cmdPattern = conf.notificationPattern();
		if (cmdPattern == null){
			ImageIcon icon = new ImageIcon(this.getClass().getResource("/information.png"));
			trayIcon = new TrayIcon(icon.getImage());
			try {
				SystemTray.getSystemTray().add(trayIcon);
			} catch (AWTException e) {
				  Log.SYS.error("Unexpected error during adding tray icon.", e);
			}
		}
	}

	public void deinit(ConfigurationProvider conf) {
		if (trayIcon != null){
			SystemTray.getSystemTray().remove(trayIcon);
		}
	}

	public void notify(String msg, String body) {
		if (cmdPattern != null){
			//use external
			callExternal(msg,body);
		} else {
			trayIcon.displayMessage(msg, body, MessageType.INFO);
		}
	}

	private void callExternal(String msg, String body) {
		String stringToExecute = cmdPattern.replace("{msg}", msg);
		stringToExecute = stringToExecute.replace("{body}", body);
		String[] splittedCmdString = stringToExecute.split(";");
		try {
			if (splittedCmdString.length > 1){
				Runtime.getRuntime().exec(splittedCmdString);
			} else {
				Runtime.getRuntime().exec(stringToExecute);
			}
		} catch (IOException e) {
			Log.SYS.error("Unexpected error during calling external notification.", e);
		}
	}

	public void notifyFaild(String msg) {
		notify(msg, "Operation faild.");
	}

}
